import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:kuwo_music/utils/common_toast.dart';

class CommonInfo with ChangeNotifier {
  Map<String, dynamic> _songInfo = {
    'percent': 0.0,
    'id': null,
  };
  Map<String, dynamic> get songInfo => _songInfo;

  void setSong(Map<String, dynamic> data) {
    _songInfo = data;
    notifyListeners();
  }

  AudioPlayerState _audioPlayerState;
  AudioPlayerState get audioPlayerState => _audioPlayerState;
  Duration _audioDuration;
  Duration get audioDuration => _audioDuration;
  Duration _audioPosition;
  Duration get audioPosition => _audioPosition;
  double get audioPercent => _audioDuration == null || _audioPosition == null
      ? 0.0
      : 100 * _audioPosition.inSeconds / _audioDuration.inSeconds;

  AudioPlayer _audioPlayer;
  AudioPlayer get audioPlayer {
    if (_audioPlayer == null) {
      // 开启调试模式：控制台自动打印
      // AudioPlayer.logEnabled = true;

      // 初始化播放器
      _audioPlayer = AudioPlayer();

      // 播放器播放状态改变
      _audioPlayer.onPlayerStateChanged.listen((AudioPlayerState state) {
        _audioPlayerState = state;
        switch (state) {
          case AudioPlayerState.PAUSED:
            {
              break;
            }
          case AudioPlayerState.PLAYING:
            {
              break;
            }
          case AudioPlayerState.STOPPED:
            {
              break;
            }
          case AudioPlayerState.COMPLETED:
            {
              break;
            }
          default:
            {}
        }
        notifyListeners();
      });

      // 播放器进度变化
      _audioPlayer.onAudioPositionChanged.listen((Duration position) {
        print(position.inSeconds / _audioDuration.inSeconds);
        _audioPosition = position;
        notifyListeners();
      });

      // 播放器音乐长度变化,开始播放新音乐
      _audioPlayer.onDurationChanged.listen((Duration duration) {
        _audioPosition = null;
        _audioDuration = duration;
        notifyListeners();
      });

      _audioPlayer.onPlayerError.listen((msg) {
        print('audioPlayer error : $msg');
        // CommonToast.showToast('获取歌曲失败！');
        clearAudio();
      });
    }
    return _audioPlayer;
  }

  void clearAudio() {
    _audioPlayerState = null;
    // _audioDuration = null;
    // _audioPosition = null;
    // _audioPlayer = null;
    notifyListeners();
  }
}
